﻿using System;
using System.Collections.Generic;
using System.Text;
using Hangfire.Console.Progress;
using Hangfire.Console;
using Hangfire.Server;
using System.Threading;

namespace NFinal.Common.TaskLogger
{
    public class HangfireLogger : ITaskLogger
    {
        public string Name { get; }
        private PerformContext context;
        public CancellationToken CancellationToken { get; }
        public HangfireLogger(PerformContext context,string name=null)
        {
            this.context = context;
            this.CancellationToken = context.CancellationToken.ShutdownToken;
            if (name == null)
            {
                this.Name = context.BackgroundJob.Id;
            }
            else
            {
                this.Name = name;
            }
        }
        public void LogExp(Exception ex)
        {
            context.WriteLine(ex.Message);
            context.WriteLine(ex.StackTrace);
        }
        public void LogExp(Exception ex, string message)
        {
            context.WriteLine(ex.Message);
            context.WriteLine(ex.StackTrace);
            context.WriteLine(message);
        }
        public void LogInfo(string message)
        {
            context.WriteLine("Info:"+message);
        }
        public void LogError(string error)
        {
            context.WriteLine("Error:"+error);
        }
        public void LogWarn(string warn)
        {
            context.WriteLine("Warn:"+warn);
        }
        private IProgressBar progressBar = null;
        public void LogPercentage(double percentage, string name=null)
        {
            if (name == null)
            {
                name = Name;
            }
            if (name == null)
            {
                if (progressBar == null)
                {
                    progressBar = context.WriteProgressBar(value: 0);
                }
                if (percentage == 100)
                {
                    progressBar.SetValue(percentage);
                    progressBar = null;
                }
            }
            else
            {
                if (progressBar==null)
                {
                    progressBar = context.WriteProgressBar(name, 0);
                }
                if (percentage == 100)
                {
                    progressBar.SetValue(percentage);
                    progressBar = null;
                }
            }
            if (progressBar != null)
            {
                progressBar.SetValue(percentage);
            }
        }

        public bool CancelCurrentTask()
        {
            return false;
        }
    }
}
